<?php
/*
 *      osmetafields.php
 *
 *      Copyright 2010 Vitaliy Rakitin <virak@ukr.net>
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

require_once($_SERVER['DOCUMENT_ROOT']."/classes/metadata/osmetafield.php");

class osmetafields {

	private $fields = array();

	function add() {
		//$uuid = genuuid();
		$field = new osmetafield();
		return $this->fields[$field->uuid] = $field;
	}
	
	function delete($uuid) {
		if (array_key_exists($uuid,$this->fields)) {
			unset($this->fields[$uuid]);
			return true;
		} return false;
/*
		foreach ($this->fields as $key=>$field) {
			if ($field->uuid == $uuid) {unset($this->fields[$key]);}
			
		}
*/
	}
	
	function byname($name) {
		foreach ($this->fields as $field) {
			if ($field->name == $name) {return $field;}
		}
		return null;
	}
	
	function byuuid($uuid) {
/*
		foreach ($this->fields as $field) {
			if ($field->uuid == $uuid) {return $field;}
		}
		return null;
*/
		if (array_key_exists($uuid,$this->fields)) {
			return $this->fields[$uuid];
		} else return null;
	}
	
	private function swap($a, $b) {
		if ($b && $a) {
			$temp = $this->fields[$a];
			$this->fields[$a] = $this->fields[$b];
			$this->fields[$b] = $temp;
		}
		//echo "swap a=$a b=$b <br>";
	}
	
	function up($uuid) {
		reset($this->fields);
		while ($field = current($this->fields)) {
			if ($field->uuid == $uuid) {
				$currkey = key($this->fields);
				prev($this->fields);
				$this->swap($currkey, key($this->fields));
				return 0;
			}
			next($this->fields);
		}
	}
	
	function down($uuid) {
		reset($this->fields);
		while ($field = current($this->fields)) {
			if ($field->uuid == $uuid) {
				$currkey = key($this->fields);
				next($this->fields);
				$this->swap($currkey, key($this->fields));
				return 0;
			}
			next($this->fields);
		}
	}
	
	function count() {
		return count($this->fields);
	}

	function getall() {
		return $this->fields;
	}
}
?>

